package com.mdxq.mall.product.service.impl;

import com.mdxq.mall.product.entity.ProductCategory;
import com.mdxq.mall.product.entity.ProductCategoryAttributeRelation;
import com.mdxq.mall.product.mapper.ProductCategoryAttributeRelationMapper;
import com.mdxq.mall.product.mapper.ProductCategoryMapper;
import com.mdxq.mall.product.service.ProductCategoryService;
import com.mybatisflex.core.paginate.Page;
import com.mybatisflex.core.query.QueryWrapper;
import com.mybatisflex.spring.service.impl.ServiceImpl;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.util.List;

/**
 * 产品分类 服务层实现。
 *
 * @author ShuJie
 * @since 2025-01-12
 */
@Service
public class ProductCategoryServiceImpl extends ServiceImpl<ProductCategoryMapper, ProductCategory>  implements ProductCategoryService{
    @Override
    public Page<ProductCategory> page(Page<ProductCategory> page) {
        QueryWrapper queryWrapper=new QueryWrapper();
        queryWrapper.eq("level",0);
        List<ProductCategory>level0=this.list(queryWrapper);
        for(ProductCategory productCategory:level0){
            queryWrapper.clear();
            queryWrapper.eq("parent_id",productCategory.getId());
            productCategory.setChildren(this.list(queryWrapper));
        }
        return new Page<>(level0,page.getPageNumber(),page.getPageNumber(),page.getPageNumber());
    }

    @Override
    public List<ProductCategory> list() {
        QueryWrapper queryWrapper=new QueryWrapper();
        queryWrapper.select("id","name");
        queryWrapper.eq("level",0);
        //queryWrapper.eq("nav_status",1);
        queryWrapper.eq("show_status",1);
        List<ProductCategory>level0=this.list(queryWrapper);
        for (ProductCategory productCategory : level0) {
            queryWrapper.clear();
            queryWrapper.select("id","name","parent_id");
            queryWrapper.eq("parent_id",productCategory.getId());
            queryWrapper.eq("show_status",1);
            productCategory.setChildren(this.list(queryWrapper));
        }
        return level0;
    }
    @Autowired
    private ProductCategoryAttributeRelationMapper relationMapper;

    @Override
    @Transactional
    public boolean update(ProductCategory productCategory) {
        updateById(productCategory);
        QueryWrapper queryWrapper=new QueryWrapper();
        queryWrapper.eq("product_category_id",productCategory.getId());
        relationMapper.deleteByQuery(queryWrapper);
        for (Long attr:productCategory.getProductAttributeIdList()){
            relationMapper.insert(new ProductCategoryAttributeRelation(null, productCategory.getId(),attr));
        }
        return false;
    }
}
